package com.yilin.commons.factory;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 司机开票资料 转 Excel
 * 工厂类
 */
public class XSSFExcelFactory {

    private XSSFWorkbook _workbook;
    private XSSFSheet _sheet;
    private String sheetName;

    public static XSSFExcelFactory newInstance(String sheetName) {
        XSSFExcelFactory _instance = new XSSFExcelFactory();
        _instance.sheetName = sheetName;
        return _instance;
    }

    private XSSFWorkbook getWorkbook() {
        if (_workbook == null) _workbook = new XSSFWorkbook();
        return _workbook;
    }

    private XSSFSheet getSheet() {
        if (_sheet == null) _sheet = getWorkbook().createSheet(sheetName);
        return _sheet;
    }

    //写入文件
    public void writeToFile(File file) {
        //将文件保存到指定的位置
        try {
            getWorkbook().write(new FileOutputStream(file));
            System.out.println("写入成功");
            getWorkbook().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 写入文件
    public MultipartFile writeToMultipartFile(HttpServletRequest request,String fileName) {
        String upLoadPath = request.getSession().getServletContext().getRealPath("");
        File file = new File(upLoadPath,fileName);
        writeToFile(file);
        DiskFileItem item = new DiskFileItem("file", MediaType.MULTIPART_FORM_DATA_VALUE,
                true, fileName, (int) file.length(), file);
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    //设置列宽 6/10/20/10/12/80
    public void setColumnWidth(Integer[] widths) {
        for (int i = 0; i < widths.length; i++) {
            getSheet().setColumnWidth(i, 256 * widths[i] + 184);
        }
    }

    //创建字体
    public XSSFFont createFont(Float fontSize) {
        return createFont(null, fontSize, false);
    }
    public XSSFFont createFont(boolean bold, Float fontSize) {
        return createFont(null, fontSize, bold);
    }

    public XSSFFont createFont(XSSFColor color, Float fontSize) {
        return createFont(color, fontSize, false);
    }

    public XSSFFont createFont(XSSFColor color, Float fontSize, boolean bold) {
        XSSFFont font = getWorkbook().createFont();
        font.setColor(color);
        if (fontSize != null) font.setFontHeightInPoints((short) fontSize.floatValue());
        font.setBold(bold);
        return font;
    }


    //创建标题 首行
    public void createBillTitle(String title, int colCount) {
        //合同单元格
        getSheet().addMergedRegion(new CellRangeAddress(0, 0, 0, colCount - 1));
        //创建标题
        XSSFRow row = getSheet().createRow(0);
        row.setHeightInPoints(48);
        XSSFCell cell = row.createCell(0);
        //标题样式
        CellStyle cellStyle = getWorkbook().createCellStyle();
        Font font = getWorkbook().createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 24);
        cellStyle.setFont(font);//增加字体样式
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(title);
    }

    //创建合计行 次行
    public void createBillStatistics(RichTextString statistics, int colCount) {
        //合同单元格
        getSheet().addMergedRegion(new CellRangeAddress(1, 1, 0, colCount - 1));
        //创建表头，也就是第一行
        XSSFRow row = getSheet().createRow(1);
        row.setHeightInPoints(32);
        XSSFCell cell = row.createCell(0);
        CellStyle cellStyle = getWorkbook().createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = getWorkbook().createFont();
        font.setFontHeightInPoints((short) 10);
        cellStyle.setFont(font);//增加字体样式
        cell.setCellStyle(cellStyle);
        cell.setCellValue(statistics);
    }

    //创建表头 第三行
    public void createBillTableHead(String[] cellLabels) {
        //创建表头，也就是第三行
        XSSFRow row = getSheet().createRow(2);
        //表头样式
        CellStyle cellStyle = getWorkbook().createCellStyle();
        Font font = getWorkbook().createFont();
        font.setFontHeightInPoints((short) 11);
        font.setBold(true);
        cellStyle.setFont(font);//增加字体样式
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        row.setHeightInPoints(28);
        for (int i = 0; i < cellLabels.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(cellLabels[i]);
            cell.setCellStyle(cellStyle);
        }
    }


    //创建表内容
    public void createBillContent(List<ContentCell[]> contentList) {
        //创建表内容，从第四行开始
        for (int i = 0; i < contentList.size(); i++) {
            XSSFRow row = getSheet().createRow(i + 3);
            for (int j = 0; j < contentList.get(i).length; j++) {
                ContentCell contentCell = contentList.get(i)[j];
                XSSFCell cell = row.createCell(j);
                //cell值
                if (contentCell.getTextCellValue() != null) {
                    cell.setCellValue(contentCell.getTextCellValue());
                } else if (contentCell.getDoubleCellValue() != null) {
                    cell.setCellValue(contentCell.getDoubleCellValue());
                } else if (contentCell.getIntCellValue() != null) {
                    cell.setCellValue(contentCell.getIntCellValue());
                } else {
                    cell.setCellValue(contentCell.getCellValue());
                }
                //cell样式
                CellStyle cellStyle = getWorkbook().createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                if (contentCell.getDataFormat() != null) {
                    XSSFDataFormat df = getWorkbook().createDataFormat();
                    cellStyle.setDataFormat(df.getFormat(contentCell.getDataFormat()));
                }
                cellStyle.setWrapText(contentCell.isWrapText());
                cellStyle.setAlignment(contentCell.getAlignment());
                cellStyle.setFont(contentCell.getFont());
                cell.setCellStyle(cellStyle);
            }
        }
    }

    public static class ContentCell {
        private RichTextString cellValue;
        private Double doubleCellValue;
        private Integer intCellValue;
        private String textCellValue;
        private HorizontalAlignment alignment = HorizontalAlignment.CENTER;
        private boolean wrapText;//自动换行
        private String dataFormat;
        private Font font;

        public String getTextCellValue() {
            return textCellValue;
        }

        public void setTextCellValue(String textCellValue) {
            this.textCellValue = textCellValue;
        }

        public Double getDoubleCellValue() {
            return doubleCellValue;
        }

        public void setDoubleCellValue(Double doubleCellValue, String dataFormat) {
            this.doubleCellValue = doubleCellValue;
            this.dataFormat = dataFormat;
        }

        public void setDoubleCellValue(Double doubleCellValue) {
            this.doubleCellValue = doubleCellValue;
        }

        public Integer getIntCellValue() {
            return intCellValue;
        }

        public void setIntCellValue(Integer intCellValue) {
            this.intCellValue = intCellValue;
        }

        public Font getFont() {
            return font;
        }

        public void setFont(Font font) {
            this.font = font;
        }

        RichTextString getCellValue() {
            return cellValue;
        }

        public void setCellValue(RichTextString cellValue) {
            this.cellValue = cellValue;
        }

        public void setAlignment(HorizontalAlignment alignment) {
            this.alignment = alignment;
        }

        HorizontalAlignment getAlignment() {
            return alignment;
        }

        boolean isWrapText() {
            return wrapText;
        }

        public void setWrapText(boolean wrapText) {
            this.wrapText = wrapText;
        }

        String getDataFormat() {
            return dataFormat;
        }

        public void setDataFormat(String dataFormat) {
            this.dataFormat = dataFormat;
        }
    }


}
